﻿using Autofac.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Threading.Tasks;
using VOL.Core.Controllers.Basic;
using VOL.Core.Filters;
using VOL.Core.ObjectActionValidator;
using VOL.Core.Services;
using VOL.Entity.DomainModels;
using VOL.System.IRepositories;
using VOL.System.IServices;

using SYSIO = System.Text;
using VOL.Core.Enums;
using VOL.Core.Utilities;
using Org.BouncyCastle.Crypto.IO;
using VOL.WebApi.Controllers.WorkOrder;
using NPOI.HPSF;
using NPOI.HSSF.Util;
using VOL.Core.Configuration;
using Microsoft.Extensions.Caching.Memory;
using System.Net;
using VOL.Core.BaseProvider;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.CacheManager;
using VOL.System.Services;
using VOL.Entity.VM;
using Microsoft.Extensions.Configuration;
using NPOI.HSSF.UserModel;
using AutoMapper;
using EasyNetQ.Internals;
using Newtonsoft.Json.Linq;
using S7.Net;
using VOL.WebApi.Extensions;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Tea;
using AlibabaCloud.SDK.Dysmsapi20170525.Models;
using NPOI.HSSF.Record;
using VOL.Core.BaseInterface;
using System.Net.Mail;
using Org.BouncyCastle.Crypto.Engines;
using System.Data.Common;
using System.Diagnostics;
using System.IO;


using System.Diagnostics;
using TDengine.Driver;
using TDengine.Driver.Client;
using Confluent.Kafka;
using FluentFTP.Helpers;
using System.Numerics;
using RestSharp;
using System.Text;
using Org.BouncyCastle.Asn1.Ocsp;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Org.BouncyCastle.Ocsp;
using Newtonsoft.Json;
using Microsoft.Web.Administration;
using EasyNetQ.Topology;
using EasyNetQ;
using System.Threading;
using VOL.WebApi.Controllers.MqDataHandle;
using System.Threading.Channels;
using RabbitMQ.Client;
using System.Collections.Concurrent;
using RabbitMQ.Client.Events;
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.EntityFrameworkCore;
using VOL.Core.EFDbContext;
using SkiaSharp;
using System.Net.Sockets;
using Microsoft.AspNetCore.SignalR;
using VOL.WebApi.Controllers.Hubs;


namespace VOL.WebApi.Controllers
{

    /// <summary>
    /// 邮件发送，短信发送，日志记录
    /// </summary>
    public partial class A_UpperComputerController :
      //ApiBaseController<Iupper_work_orderService>
      ApiBaseController<ISys_UserService>
    {

        private readonly Iupper_ftpmachiningcenterRepository _repository;//访问数据库

        private static int count = 0;
        // 注入 IServiceScopeFactory

        public A_UpperComputerController(Iupper_ftpmachiningcenterRepository dbRepository,
            IHttpContextAccessor httpContextAccessor) 
        {
    
            _repository = dbRepository;
          
        }
        /// <summary>
        /// 拦截
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>
        [HttpPost, Route("PROCESS_INTERCEPTION")]
        public async Task<object> PROCESS_INTERCEPTION(string message)
        {
            string msg = string.Empty;

            var rs = new WebResponseContent();
            try
            {
             
                // 创建复杂条件表达式:
                // (工序 == "电镀" OR 工序结尾为"处理") 
                // AND 
                // (尺寸 > 10.0 OR 批次号包含"REJECT") 
                // AND 
                // NOT (紧急订单 == true)
                var condition = new AndCondition().AddCondition(
                    new OrCondition()
                        .AddCondition(new NumericCondition("尺寸", 10,
                                ConditionOperator.Equal, 10.0))

                );

                var timeCondition = new TimeRangeCondition("生产时间", DateTime.Now,
new TimeSpan(8, 0, 0), new TimeSpan(17, 0, 0));

                var shiftCondition = CompositeCondition.CreateShiftCondition("中班", DateTime.Now);

                var complexCondition = new AndCondition()
                //.AddCondition(condition)
                .AddCondition(timeCondition)
                //  .AddCondition(shiftCondition)
                ;
                //var condition = new AndCondition()
                //    .AddCondition(
                //        new OrCondition()
                //            .AddCondition(new ProcessCondition("工序", "电镀处理",
                //                new[] { "电镀" }, ConditionOperator.Contains))
                //            .AddCondition(new ProcessCondition("工序", "电镀处理",
                //                new[] { "处理" }, ConditionOperator.EndsWith))
                //    )
                //    .AddCondition(
                //        new OrCondition()
                //            .AddCondition(new NumericCondition("尺寸", 10.5,
                //                ConditionOperator.GreaterThan, 10.0))
                //            .AddCondition(new TextCondition("批次号", "REJECT-2023-456",
                //                ConditionOperator.Contains, "REJECT"))
                //    )
                //    .AddCondition(
                //        new NotCondition(
                //            new BooleanCondition("紧急订单", ConditionOperator.Equal, true)
                //        )
                //    );

                //var builder = new ConditionBuilder().SetRoot(condition);
                var builder = new ConditionBuilder().SetRoot(complexCondition);
                Console.WriteLine("复杂条件拦截系统");
                Console.WriteLine("========================");
                builder.VisualizeExpressionTree();

                // 模拟实际拦截逻辑
                if (builder.Evaluate())
                {
                    Console.WriteLine("\n>>> 触发拦截条件，执行拦截操作! <<<");
                }
                else
                {
                    Console.WriteLine("\n>>> 条件未满足，继续执行流程 <<<");
                }
                rs.Message = "发送成功";
                rs.Status = true;



            }
            catch (Exception)
            {

                rs.Status = false;
            }
            return rs;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpGet("PushMsg")]
        public async Task<IActionResult> PushMsg([FromQuery] string content)
        {
            //await _hubContext.Clients.All.SendAsync("ShowMsg", new MsgInfo { Title = ":", MsgContent = content + count++ });
            await _hubContext.Clients.All.SendAsync("ShowMsg", new MsgInfo { Title = ":", MsgContent = content });
            return Ok();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpGet("PushMsg1")]
        public async Task<IActionResult> PushMsg1([FromQuery] string content)
        {
            //await _hubContext.Clients.All.SendAsync("ShowMsg1", new MsgInfo { Title = ":", MsgContent = content + count++ });
            await _hubContext.Clients.All.SendAsync("ShowMsg1", new MsgInfo { Title = ":", MsgContent = content });
            return Ok();
        }
        /// <summary>
        /// MQProMessage
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>
        [HttpPost, Route("MQProMessage")]
        public async Task<object> MQProMessage(string message)
        {
            string msg = string.Empty;

            var rs = new WebResponseContent();
            try
            {
                // 创建连接工厂（修改为你的RabbitMQ服务器地址）
                SendMessage(message);
                rs.Message = "发送成功";
                rs.Status = true;



            }
            catch (Exception)
            {

                rs.Status = false;
            }
            return rs;
        }

        //   private static IConnection _connection;
        //  private static IModel _channel;

        public static void SendMessage(string message)
        {
            IConfigurationSection section = AppSetting.GetSection("MQ");
            var hostName = section["HostName"];
            var port = section["Port"];
            var userName = section["UserName"];
            var password = section["Password"];
            var factory = new ConnectionFactory()
            {
                AutomaticRecoveryEnabled = true,
                HostName = hostName,
                Port = 5672,
                UserName = userName,
                Password = password
            };

            try
            {
                if (_connection?.IsOpen != true)
                {
                    _connection = factory.CreateConnection();
                    _channel = _connection.CreateModel();
                }

                var body = Encoding.UTF8.GetBytes(message);

                // 使用事务确保消息到达
                _channel.TxSelect();
                _channel.BasicPublish("", "demo_queue", null, body);
                _channel.TxCommit();

                Console.WriteLine($"已发送: {message}");
            }
            catch (Exception ex)
            {
                _channel?.TxRollback();
                Console.WriteLine($"发送失败: {ex.Message}");
                Reconnect();
            }
        }

        private static void Reconnect()
        {
            _channel?.Dispose();
            _connection?.Dispose();
            // 重新初始化连接
            SendMessage("重连测试消息");
        }
        private static void CreateChannel()
        {
            if (_channel?.IsOpen ?? false) return;

            _channel = _connection.CreateModel();
            _channel.ModelShutdown += (sender, e) =>
                Console.WriteLine($"通道关闭原因: {e.ReplyText}");
        }
        private static IConnection _connection;
        private static IModel _channel;
        private static EventingBasicConsumer _consumer;
        private static string _consumerTag;
        private static readonly object _lock = new object();
        /// <summary>
        /// MQCursterMessage
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>
        [HttpPost, Route("MQCursterMessage")]
        public async Task<object> MQCursterMessage()
        {
           
            string msg = string.Empty;
            IConfigurationSection section = AppSetting.GetSection("MQ");
            var hostName = section["HostName"];
            var port = section["Port"];
            var userName = section["UserName"];
            var password = section["Password"];
            // var bus = RabbitHutch.CreateBus("host=" + hostName + ";username=admin;password=123456");
            var rs = new WebResponseContent();
            try
            {
                var factory = new ConnectionFactory()
                {
                    HostName = hostName,
                    Port = 5672,
                    UserName = userName,
                    Password = password,
                    AutomaticRecoveryEnabled = true, // 启用自动重连
                    NetworkRecoveryInterval = TimeSpan.FromSeconds(10) // 重连间隔
                };

                // 创建持久连接
                _connection = factory.CreateConnection();
                _connection.ConnectionShutdown += (sender, e) =>
                    Console.WriteLine($"连接关闭原因: {e.ReplyText}");

                // 创建通道
                CreateChannel();

                // 声明队列
                _channel.QueueDeclare("demo_queue", durable: true, exclusive: false, autoDelete: false);

                var consumer = new EventingBasicConsumer(_channel);
                consumer.Received += (model, ea) =>
                {
               
                        try
                        {
                            // 加锁确保线程安全
                            lock (_lock)
                            {
                                if (!_channel.IsOpen)
                                {
                                    Console.WriteLine("通道已关闭，重新创建");
                                    CreateChannel();
                                    return;
                                }

                                var message = SYSIO.Encoding.UTF8.GetString(ea.Body.ToArray());
                            _messageQueue.Enqueue(message);
                            //_userRepository.DbContext.Database.cre;
                            // 每次处理消息时重新获取实体，避免并发问题
                            //  _repository.DbContext.Set<INTE_SHELVES>().ToList();
                            //   var equipment=_repository.DbContext.Set<EQU_EQUIPMENT>().Where(t=> t.EquipmentCode== "YDD_001").FirstOrDefault();
                            //if (equipment != null)
                            //    {
                            //        equipment.LastUpdateOn = DateTime.Now;
                            //        equipment.UpdateBy = message;
                            //    _userRepository.Update(equipment);
                            //    _userRepository.SaveChanges(); // 确保立即保存
                            //    }

                            // 模拟处理耗时
                                Thread.Sleep(1000);

                                _channel.BasicAck(ea.DeliveryTag, false);
                            }

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"处理失败: {ex.Message}");
                            // 添加重试次数检查
                            if (ea.BasicProperties.Headers == null || !ea.BasicProperties.Headers.TryGetValue("retry-count", out var retryObj) || (int)retryObj < 3)
                            {
                                retryObj = 0;
                                var retryCount = (retryObj as int?) ?? 0;
                                var properties = _channel.CreateBasicProperties();
                                properties.Headers = new Dictionary<string, object> { { "retry-count", retryCount + 1 } };
                                _channel.BasicPublish("", "demo_queue", properties, ea.Body);
                            }
                            _channel.BasicNack(ea.DeliveryTag, false, false); // 不重新入队，由重试逻辑处理
                                                                              // _channel.BasicNack(ea.DeliveryTag, false, true); // 消息重新入队
                        }
                    
                };
         
                _channel.BasicConsume("demo_queue", autoAck: false, consumer);

            

            }
            catch (Exception)
            {

                rs.Status = false;

            }
            finally
            {
                // 优雅关闭资源
                if (_channel?.IsOpen ?? false)
                {
                    _channel.BasicCancel(_consumerTag); // 停止消费
                    _channel.Close();
                }
                _connection?.Close();
            }
            return rs;
        }


        private static readonly int Port = 4000;
        private static TcpListener? server;
        private static bool isRunning = true;


        /// <summary>
        /// SocketServer
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>
        [HttpPost, Route("SocketServer")]
        public async Task<object> SocketServer()
        {
            string msg = string.Empty;

            var rs = new WebResponseContent();
            try
            {
                // 创建连接工厂（修改为你的RabbitMQ服务器地址）
                MainServer();
                rs.Message = "发送成功";
                rs.Status = true;



            }
            catch (Exception)
            {

                rs.Status = false;
            }
            return rs;
        }
        static void MainServer()
        {
            // 定义IP地址和端口号
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); // 本地回环地址
            int port = 4000;

            // 创建Socket对象
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 绑定IP地址和端口号
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            // 开始监听连接请求
            serverSocket.Listen(10);

            Console.WriteLine("Server started. Waiting for a connection...");

            while (true)
            {
                // 接受来自客户端的连接请求
                Socket clientSocket = serverSocket.Accept();
                Console.WriteLine("Client connected.");

                // 处理客户端连接，通常在一个新的线程中处理，以避免阻塞服务器
                Thread clientThread = new Thread(() => HandleClient(clientSocket));
                clientThread.Start();
            }
        }
        //static async Task Main()
        //{
        //    try
        //    {
        //        server = new TcpListener(IPAddress.Any, Port);
        //        server.Start();
        //        Console.WriteLine($"服务器已启动，监听端口: {Port}");

        //        while (isRunning)
        //        {
        //            Console.WriteLine("等待客户端连接...");
        //            TcpClient client = await server.AcceptTcpClientAsync();
        //            _ = HandleClientAsync(client);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"服务器错误: {ex.Message}");
        //    }
        //    finally
        //    {
        //        server?.Stop();
        //    }
        //}
        private static void HandleClient(Socket clientSocket)
        {
            try
            {
                byte[] buffer = new byte[1024];
                int received;
                while ((received = clientSocket.Receive(buffer)) != 0)
                {
                    // 将接收到的数据转换为字符串并打印
                    string text = Encoding.ASCII.GetString(buffer, 0, received);
                    Console.WriteLine("Received: " + text);
                    // 发送响应数据到客户端（可选）
                    byte[] msg = Encoding.ASCII.GetBytes("Hello from server");
                    clientSocket.Send(msg);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
            finally
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
            }
        }
        private static async Task HandleClientAsync(TcpClient client)
        {
            try
            {
                using NetworkStream stream = client.GetStream();
                byte[] buffer = new byte[1024];
                string clientEndPoint = client.Client.RemoteEndPoint?.ToString() ?? "未知客户端";
                Console.WriteLine($"客户端已连接: {clientEndPoint}");

                while (client.Connected)
                {
                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0) break;

                    string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"收到消息: {message}");

                    // 发送响应
                    string response = $"服务器已收到消息: {message}";
                    byte[] responseData = Encoding.UTF8.GetBytes(response);
                    await stream.WriteAsync(responseData, 0, responseData.Length);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理客户端时出错: {ex.Message}");
            }
            finally
            {
                string remoteEndPoint = client.Client.RemoteEndPoint?.ToString() ?? "未知客户端";
                client.Close();
                Console.WriteLine($"客户端断开连接: {remoteEndPoint}");
            }
        }


        /// <summary>
        /// SockeClient
        /// </summary>
        /// <param name="clientDto"></param>
        /// <returns></returns>
        [HttpPost, Route("SockeClient")]
        public async Task<object> SockeClient()
        {
            string msg = string.Empty;

            var rs = new WebResponseContent();
            try
            {
                // 创建连接工厂（修改为你的RabbitMQ服务器地址）
                 MainClient();
                rs.Message = "发送成功";
                rs.Status = true;



            }
            catch (Exception)
            {

                rs.Status = false;
            }
            return rs;
        }
       static Socket client = null;
        static  void MainClient()
        {
      


            // 创建Socket对象
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 连接到服务器（IP地址和端口号）
            clientSocket.Connect("127.0.0.1", 4000); // 确保这里的IP地址和端口与服务器端一致
            Console.WriteLine("Connected to server.");

            // 发送消息到服务器
            string message = "Hello from client";
            byte[] msg = Encoding.ASCII.GetBytes(message);
            clientSocket.Send(msg);
            Console.WriteLine("Sent: " + message);

            // 接收服务器的响应（可选）
            byte[] buffer = new byte[1024];
            int received = clientSocket.Receive(buffer);
            string response = Encoding.ASCII.GetString(buffer, 0, received);
            Console.WriteLine("Received: " + response);

            // 关闭连接
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }


    }

    


}
